package com.leyou.user.controller;

import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.pojo.AddressDTO;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 用户控制器
 */
@RestController
@Api(description = "用户控制器")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 校验数据是否可用
     */
    @GetMapping("/check/{data}/{type}")
    @ApiOperation("用户注册数据校验")
    public ResponseEntity<Boolean> checkData(
            @PathVariable("data") @ApiParam("用户名或手机号码") String data,
            @PathVariable("type") @ApiParam("验证类型，1或2") Integer type){
        Boolean isCanUse = userService.checkData(data,type);
        return ResponseEntity.ok(isCanUse);
    }

    /**
     * 发送手机验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCodeMsg(@RequestParam("phone") String phone){
        userService.sendCodeMsg(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 用户注册
     * BindingResult: 用于封装@Valid验证失败后的错误内容
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        if(result.hasErrors()){
            String errorMsg = result.getFieldErrors()
                    .stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(500,errorMsg);
        }

        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 校验用户名和密码是否正确
     */
    @GetMapping("/query")
    public ResponseEntity<User> query(
            @RequestParam("username") String username,
            @RequestParam("password") String password){
        User loginUser = userService.query(username,password);
        return ResponseEntity.ok(loginUser);
    }

    /**
     * 查询指定用户的收货地址
     */
    @GetMapping("/address")
    public ResponseEntity<AddressDTO> findAddressById(
            @RequestParam("userId") Long userId,
            @RequestParam("id") Long id){
        AddressDTO addressDTO = userService.findAddressById(userId,id);
        return ResponseEntity.ok(addressDTO);
    }
}
